<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Adv;
use App\Model\Advcontent;

class AdvController extends Controller
{
  // 获取广告位列表
  public function getAdvList()
  {
    $adv = Adv::get();
    return response()->json(['status' => 200, 'data' => $adv]);
  }

  // 根据id获取广告位
  public function getAdvById($id)
  {
    $adv = Adv::where('id', $id)->first();
    if (!$adv) return response()->json(['status' => 400, 'msg' => '获取广告位失败']);
    return response()->json(['status' => 200, 'data' => $adv]);
  }

  // 添加广告位
  public function addAdv(Request $request)
  {
    $adv = $request->all();
    $res = Adv::create($adv);
    // 判断添加是否成功
    if (!$res) return response()->json(['status' => 400, 'msg' => '添加广告位失败']);
    return response()->json(['status' => 200, 'msg' => '添加广告位成功']);
  }

  // 根据id修改广告位
  public function updateAdvById(Request $request, $id)
  {
    $name = $request->get('name');
    $res = Adv::where('id', $id)->update([
      'name' => $name
    ]);
    // 判断修改是否成功
    if (!$res) return response()->json(['status' => 400, 'msg' => '修改广告位失败']);
    return response()->json(['status' => 200, 'msg' => '修改广告位成功']);
  }

  // 根据id删除广告位
  public function deleteAdvById($id)
  {
    // 根据广告位id获取广告内容
    $data = Advcontent::where('advid', $id)->get();
    // 判断当前广告位下是否存在内容
    if (count($data) > 0) return response()->json(['status' => 400, 'msg' => '当前广告位下存在内容']);
    $res = Adv::where('id', $id)->delete();
    // 判断删除是否成功
    if (!$res) return response()->json(['status' => 400, 'msg' => '删除广告位失败']);
    return response()->json(['status' => 200, 'msg' => '删除广告位成功']);
  }
}
